﻿using System;
using System.Data;
using System.Diagnostics;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using GatewayInspect.Modules;
using Excel = Microsoft.Office.Interop.Excel;

namespace GatewayInspect.Common
{
    public class ModuleUtils
    {
        public static IModule CreateModule(string sClassName)
        {
            Assembly _assembly = Assembly.GetExecutingAssembly();
            string sFullName = _assembly.GetName().Name + ".Modules." + sClassName;
            IModule iModule = null;
            Type type = _assembly.GetType(sFullName);
            if (type != null)
            {
                iModule = Activator.CreateInstance(type) as IModule;
            }
            return iModule;
        }

        public static DataTable GetDataTableFromExcel(string strFilePath, bool hasTitle = false)
        {
            Excel.Application app = new Excel.Application();
            object oMissiong = System.Reflection.Missing.Value;
            Excel.Workbook workbook = null;
            DataTable dt = new DataTable();

            try
            {
                if (app == null) return null;
                workbook = app.Workbooks.Open(strFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong,
                    oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
                Excel.Sheets sheets = workbook.Worksheets;

                //将数据读入到DataTable中
                Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);//读取第一张表  
                if (worksheet == null) return null;

                int iRowCount = worksheet.UsedRange.Rows.Count;
                int iColCount = worksheet.UsedRange.Columns.Count;
                //生成列头
                for (int i = 0; i < iColCount; i++)
                {
                    var name = "column" + i;
                    if (hasTitle)
                    {
                        var txt = ((Excel.Range)worksheet.Cells[1, i + 1]).Text.ToString();
                        if (!string.IsNullOrWhiteSpace(txt)) name = txt;
                    }
                    while (dt.Columns.Contains(name)) name = name + "_1";//重复行名称会报错。
                    dt.Columns.Add(new DataColumn(name, typeof(string)));
                }
                //生成行数据
                Excel.Range range;
                int rowIdx = hasTitle ? 2 : 1;
                for (int iRow = rowIdx; iRow <= iRowCount; iRow++)
                {
                    DataRow dr = dt.NewRow();
                    for (int iCol = 1; iCol <= iColCount; iCol++)
                    {
                        range = (Excel.Range)worksheet.Cells[iRow, iCol];
                        dr[iCol - 1] = (range.Value2 == null) ? "" : range.Text.ToString();
                    }
                    dt.Rows.Add(dr);
                }
                return dt;
            }
            catch { return null; }
            finally
            {
                workbook.Close(false, oMissiong, oMissiong);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                workbook = null;
                app.Workbooks.Close();
                app.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                app = null;

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        public static void DownUpFile(string _straddress)
        {
            string localFilePath = "";
            string FilePath = "";
            string fileaddress = _straddress;
            if (!fileaddress.Equals(""))
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                //设置文件类型 
                saveFileDialog1.FileName = fileaddress.Substring(fileaddress.LastIndexOf("/") + 1);
                saveFileDialog1.Filter = " txt files(*.txt)|*.txt|All files(*.*)|*.*";
                //设置默认文件类型显示顺序 
                saveFileDialog1.FilterIndex = 2;
                //保存对话框是否记忆上次打开的目录 
                saveFileDialog1.RestoreDirectory = true;
                //点了保s存按钮进入
                string _fileName = "";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    //获得文件路径  
                    localFilePath = saveFileDialog1.FileName.ToString();
                    FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));
                    _fileName = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);
                    Download(fileaddress, FilePath, _fileName);
                }
                try
                {
                    Process p = new Process();
                    p.StartInfo.FileName = FilePath + "//" + _fileName; //fileaddress.Substring(fileaddress.LastIndexOf("/") + 1);//System.Windows.Forms.Application.StartupPath.ToString() + this.View.ThislistView.SelectedItems[0].SubItems[4].Text;
                    p.Start();
                }
                catch (Exception ex)
                {
                    //   MessageBox.Show("文件丢失");
                }
            }
            else
            {
                MessageBox.Show("文件还未上传到服务器");
            }
        }

        /// <summary>
        /// 下载服务器文件至客户端
        /// </summary>
        /// <param name="URL">被下载的文件地址，绝对路径</param>
        /// <param name="Dir">另存放的目录</param>
        private static void Download(string URL, string Dir, string _FileNmae)
        {
            WebClient client = new WebClient();
            string Path = Dir + "\\" + _FileNmae; //另存为的绝对路徑＋文件名
            try
            {
                WebRequest myre = WebRequest.Create(URL);
            }
            catch
            {
                // MessageBox.Show(exp.Message,"Error");
            }
            try
            {
                client.DownloadFile(URL, Path);
            }
            catch
            {
                // MessageBox.Show(exp.Message,"Error");
            }
        }

        /// <summary>
        /// 获取活动窗体句柄
        /// </summary>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetForegroundWindow();
    }
}
